<template>
  <div class="app-container">
    <!-- <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
    >
      <el-form-item label="名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          size="small"
        >
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</el-button
        >
        <el-button plain size="mini" @click="handleSelectAll">全选</el-button>
        <el-button plain size="mini" :disabled="multiple" @click="handleDelete"
          >删除</el-button
        >
        <el-button plain size="mini" :disabled="multiple" @click="handleMove"
          >批量移动</el-button
        >
        <treeselect
          v-model="newCategoryId"
          :normalizer="normalizer"
          :flat="true"
          :append-to-body="true"
          :options="pCategoryList"
          :show-count="true"
          placeholder="请选择类别"
          :default-expand-level="2"
        />
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      ref="table"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      :data="list"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
      ></el-table-column>
      <el-table-column prop="id" label="编号" width="260" />
      <el-table-column prop="title" label="重要通知" width="200" />

      <!-- <el-table-column prop="orderNum" label="型号/名称	" width="200" />
      <el-table-column prop="orderNum" label="描述" width="200" />
      <el-table-column prop="orderNum" label="大小" width="200" /> -->

      <el-table-column
        label="发布日期"
        align="center"
        prop="createTime"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog
      fullscreen
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <!-- <el-col :span="24">
            <el-form-item label="文件标题" prop="title">
              <el-input
                type="textarea"
                style="width:500px;"
                v-model="form.title"
                placeholder="请输入文件标题"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="所属分类" prop="categoryId">
              <el-cascader
                :props="props"
                v-model="form.categoryId"
                :options="category"
                :show-all-levels="false"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件" prop="cmsAttachmentList">
              <FileUpload v-model="form.cmsAttachmentList" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getArticlePage,
  addArticle,
  getArticle,
  delArticle,
  putArticle
} from "@/api/cms/article";

import {
  getAttachmentPage,
  addAttachment,
  getAttachment,
  delAttachment,
  putAttachment
} from "@/api/cms/attachment";

import { getPage as getCategoryPage } from "@/api/cms/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import FileUpload from "@/components/FileUpload";
import { setTreeLevel } from "@/utils/ruoyi";

export default {
  name: "DocumentList",
  components: {
    FileUpload,
    Treeselect
  },
  data() {
    return {
      props: {
        label: "categoryName",
        value: "categoryId"
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      list: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        category:""
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        cmsAttachmentList: [
          // {
          //   fileDesc: "string",
          //   fileName: "string",
          //   fileType: "string",
          //   fileUrl: "string",
          //   size: "string"
          // }
        ]
      },
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "上级不能为空", trigger: "blur" }
        ],
        title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        remark: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        top: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      },
      category: [],
      ids: [],
      single: true,
      multiple: true,
      pCategoryList: [],
      newCategoryId: undefined
    };
  },
  created() {
    // const index = this.$route.path.indexOf("list");
    // const categoryId = this.$route.path.slice(index + 4);
    this.queryParams.category = 1;
    this.getList(); 
    function getPid(list, cid) {
      let result = 0;
      list.forEach(item => {
        if (item.categoryId == cid) {
          result = item.categoryId;
          if (item.parentId != 0) {
            result = getPid(list, item.parentId);
          }
        }
      });
      return result;
    }
    getCategoryPage().then(response => {
      const pid = getPid(response.data, categoryId);
      console.log(pid, "pid");
      this.category = setTreeLevel(
        this.handleTree(response.data, "categoryId")
      );
      this.pCategoryList = this.category.filter(item => item.categoryId == pid);
    });
  },
  methods: {
    normalizer(node) {
      console.log(node);
      if (node.children && !node.children.length) {
        delete node.children;
      }
      const p = {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children
      };
      !node.isLast ? (p.isDisabled = true) : "";
      return p;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getAttachmentPage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: undefined,
        title: undefined,
        remark: undefined,
        top: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getArticle(row.id).then(response => {
        let temp = 1;
        response.data.cmsAttachmentList = response.data.cmsAttachmentList
          .filter(item => !!item.fileUrl)
          .map(item => {
            item.fileDate = item.createTime;
            item.fileDesc = item.fileDesc;
            item.name = item.fileName;
            item.fileName = item.fileName;
            item.fileType = item.fileType;
            item.fileUrl = item.fileUrl;
            item.url = item.fileUrl;
            item.size = item.size;
            item.uid = new Date().getTime() + temp++;
            return item;
          });
        this.form = response.data;
        this.open = true;
        this.title = "修改信息";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const categoryId = this.form.categoryId[
            this.form.categoryId.length - 1
          ];
          const cmsAttachmentList = this.form.cmsAttachmentList.map(item => {
            return {
              fileDesc: item.fileDesc,
              fileName: item.fileName,
              fileType: item.fileType,
              fileUrl: item.fileUrl,
              fileDate: item.fileDate,
              size: item.size
            };
          });
          if (this.form.id != undefined) {
            putArticle({ ...this.form, categoryId, cmsAttachmentList }).then(
              response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            );
          } else {
            addArticle({ ...this.form, categoryId, cmsAttachmentList }).then(
              response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            );
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除名称为"' + row.deptName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delArticle(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleSelectAll() {
      this.$refs.table.toggleAllSelection();
    },
    handleMove() {
      if (!this.newCategoryId) {
        this.$message.error("请选择新的分类");
        return;
      }
      changeCategory(this.ids, this.form.categoryId).then(response => {
        this.msgSuccess("移动成功");
        this.getList();
      });
    }
  }
};
</script>
